package com.hmall.gateway.filter;

import com.hmall.gateway.properties.AuthProperties;
import com.hmall.gateway.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * 全局鉴权过滤器
 * @author
 * @version 1.0.1
 * @date 2024-10-10 17:33:09
 */
//@Component
@Order(0)
@Slf4j
@RequiredArgsConstructor
public class AuthGlobalFilter implements GlobalFilter {

    private final AuthProperties authProperties;
    private final JwtTool jwtTool;
    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    /**
     * 全局过滤方法
     * @param exchange 封装了请求与响应的对象
     * @param chain 过滤器链对象
     * @return 返回执行下一个过滤器的对象
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1.判断是否是要拦截的路径
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String url = request.getPath().toString();
        //log.info("url:{}", url);
        // 2.不是：直接放行
        if(isExclude(url)){
            //log.info("放行的url:{}", url);
            return chain.filter(exchange);
        }
        // 3.是：获取请求头，鉴权
        //log.info("要鉴权的url:{}", url);
        // 3.1 获取请求头
        String token = request.getHeaders().getFirst("authorization");
        // 3.2 鉴权
        Long userId = null;
        try {
            userId = jwtTool.parseToken(token);
            String userInfo = userId.toString();
            // 3.3 token合法，获取userId，传递到下一个微服务
            exchange.mutate()
                    //增加一个请求头
                    .request(b -> b.header("user-info", userInfo))
                    .build();
        } catch (Exception e) {
            //throw new RuntimeException(e);
            // 3.4 token非法，返回401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        return chain.filter(exchange);
    }

    private boolean isExclude(String url) {
        List<String> paths = authProperties.getExcludePaths();
        for (String path : paths) {
            if (antPathMatcher.match(path, url)) {
                //匹配成功，返回true
                return true;
            }
        }
        //全部都没有匹配成功，才返回false
        return false;
    }
}












